# -*- coding: utf-8 -*-

import sys
import os.path
from PyQt6 import QtCore, QtGui, QtWidgets
import random_extract


class Ui_MainWindow(object):
    def __init__(self, VERSION="") -> None:
        self.RANDOM_OBJ = random_extract.RandomSelector()
        self.max_num_in = len(self.RANDOM_OBJ.name_list_from_file)
        self.max_num_jp = len(self.RANDOM_OBJ.name_list_no_jp)
        self.max_num = self.max_num_in
        self.VERSION = VERSION
        self.lastlist = []

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
        MainWindow.resize(620, 640)
        MainWindow.setMinimumSize(QtCore.QSize(620, 640))
        MainWindow.setMaximumSize(QtCore.QSize(620, 640))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(16)
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.chouquanniu = QtWidgets.QPushButton(parent=self.centralwidget)
        self.chouquanniu.setGeometry(QtCore.QRect(150, 580, 61, 41))
        self.chouquanniu.setObjectName("chouquanniu")
        self.output_display = QtWidgets.QTextBrowser(parent=self.centralwidget)
        self.output_display.setGeometry(QtCore.QRect(220, 10, 381, 621))
        font = QtGui.QFont()
        font.setFamily("微软雅黑")
        font.setPointSize(24)
        self.output_display.setFont(font)
        self.output_display.setDocumentTitle("")
        self.output_display.setMarkdown("")
        self.output_display.setObjectName("output_display")
        self.horizontalLayoutWidget = QtWidgets.QWidget(parent=self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(20, 519, 191, 51))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtWidgets.QLabel(parent=self.horizontalLayoutWidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.number_input = QtWidgets.QSpinBox(parent=self.horizontalLayoutWidget)
        self.number_input.setButtonSymbols(
            QtWidgets.QAbstractSpinBox.ButtonSymbols.NoButtons
        )
        self.number_input.setMinimum(1)
        self.number_input.setMaximum(self.max_num)
        self.number_input.setObjectName("number_input")
        self.horizontalLayout.addWidget(self.number_input)
        self.pushButton_2 = QtWidgets.QPushButton(parent=self.horizontalLayoutWidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton_3 = QtWidgets.QPushButton(parent=self.horizontalLayoutWidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout.addWidget(self.pushButton_3)
        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(parent=self.centralwidget)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(20, 470, 191, 51))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_2 = QtWidgets.QLabel(parent=self.horizontalLayoutWidget_2)
        self.label_2.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_2.addWidget(self.label_2)
        self.total_count = QtWidgets.QLabel(parent=self.horizontalLayoutWidget_2)
        self.total_count.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.total_count.setObjectName("total_count")
        self.horizontalLayout_2.addWidget(self.total_count)
        self.label_4 = QtWidgets.QLabel(parent=self.horizontalLayoutWidget_2)
        self.label_4.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_2.addWidget(self.label_4)
        self.verticalLayoutWidget = QtWidgets.QWidget(parent=self.centralwidget)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 380, 193, 80))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.paichuriyu = QtWidgets.QCheckBox(parent=self.verticalLayoutWidget)
        self.paichuriyu.setObjectName("paichuriyu")
        self.verticalLayout.addWidget(self.paichuriyu)
        self.exclude_previously_drawn = QtWidgets.QCheckBox(
            parent=self.verticalLayoutWidget
        )
        self.exclude_previously_drawn.setChecked(True)
        self.exclude_previously_drawn.setObjectName("exclude_previously_drawn")
        self.verticalLayout.addWidget(self.exclude_previously_drawn)
        self.chongzhipaichu = QtWidgets.QPushButton(parent=self.centralwidget)
        self.chongzhipaichu.setEnabled(True)
        self.chongzhipaichu.setGeometry(QtCore.QRect(44, 580, 101, 41))
        self.chongzhipaichu.setCheckable(False)
        self.chongzhipaichu.setAutoExclusive(False)
        self.chongzhipaichu.setAutoDefault(False)
        self.chongzhipaichu.setObjectName("chongzhipaichu")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.pushButton_2.clicked.connect(self.number_input.stepUp)  # type: ignore
        self.pushButton_3.clicked.connect(self.number_input.stepDown)  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        # 抽取主按钮
        self.chouquanniu.clicked.connect(self.chouqu)
        # 重置上次
        self.chongzhipaichu.clicked.connect(self.reset_last)
        self.paichuriyu.clicked.connect(self.riyumaxnum)

    def riyumaxnum(self):
        isJP = self.paichuriyu.isChecked()
        if isJP:
            self.max_num = self.max_num_jp
            self.number_input.setMaximum(self.max_num)
            self.total_count.setText(str(self.max_num))
        else:
            self.max_num = self.max_num_in
            self.number_input.setMaximum(self.max_num)
            self.total_count.setText(str(self.max_num))

    # 定义一个名为chouqu的方法，该方法在点击抽奖按钮后会被调用
    def chouqu(self, MainWindow):
        # 获取用户通过界面输入的参与抽奖人数
        num_people = self.number_input.value()

        # 调用get_random_result方法生成随机抽奖结果列表
        random_list = self.get_random_result(num_people)

        # 移除每项结果末尾的「*日」
        cleaned_random_list = [
            result[:-2] if result.endswith("*日") else result for result in random_list
        ]

        # 生成一个字符串，用于呈现随机列表内容的结果
        random_str = "结果为：\n"
        random_str += "\n".join(
            f"{i}. {result}" for i, result in enumerate(cleaned_random_list, start=1)
        )

        # 更新输出区域文本内容为随机抽奖结果
        self.update_text(random_str)

    # 定义一个用于生成指定数量随机抽奖结果的方法
    def get_random_result(self, num_people):
        # 获取是否排除日语
        isJP = self.paichuriyu.isChecked()
        # 检查是否勾选了排除上次已抽出选项
        if self.exclude_previously_drawn.isChecked():
            # 若勾选，则调用RANDOM_OBJ对象的get_random_result_rmlast方法，排除上次已抽的结果
            random_list = self.RANDOM_OBJ.get_random_result_rmlast(
                num_people, self.lastlist, isJP
            )

            # 更新最后抽取结果列表（lastlist），并追加本次新抽取的结果
            self.lastlist.extend(random_list)

            # 更新剩余可抽取人数显示（total_count）：总名额减去已抽名单长度
            self.total_count.setText(
                str(self.max_num - len(self.lastlist)) + "/" + str(self.max_num)
            )
        else:
            # 若未勾选排除选项，则直接调用RANDOM_OBJ对象的get_random_result方法获取新结果
            random_list = self.RANDOM_OBJ.get_random_result(num_people, isJP)

        # 返回随机抽奖结果列表
        return random_list

    # 定义一个更新输出文本框内容的方法
    def update_text(self, text):
        # 设置输出展示区域（output_display）的纯文本内容为传入的text参数值
        self.output_display.setPlainText(text)

    # 定义一个重置上次抽取结果的方法
    def reset_last(self, MainWindow):
        # 清空已抽取结果列表（lastlist）
        self.lastlist = []

        # 由于lastlist已被清空，所以将剩余可抽取人数显示设置为最大名额数
        self.total_count.setText(str(self.max_num))

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("MainWindow", f"点人 - {self.VERSION} - ©Cool-GK")
        )
        self.chouquanniu.setText(_translate("MainWindow", "抽取"))
        self.label.setText(_translate("MainWindow", "人数"))
        self.pushButton_2.setText(_translate("MainWindow", "+"))
        self.pushButton_3.setText(_translate("MainWindow", "-"))
        self.label_2.setText(_translate("MainWindow", "一共有"))
        self.label_4.setText(_translate("MainWindow", "人"))
        self.paichuriyu.setText(_translate("MainWindow", "排除日语"))
        self.exclude_previously_drawn.setText(
            _translate("MainWindow", "排除已经抽过的人")
        )
        self.chongzhipaichu.setText(_translate("MainWindow", "重置排除"))
        self.total_count.setText(_translate("MainWindow", str(self.max_num)))


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    VERSION = "24Y15WA"

    # 判断抽取列表是否存在
    if not os.path.exists("抽取列表.txt"):
        QtWidgets.QMessageBox.critical(
            None, "错误", "找不到 「抽取列表.txt」 文件，无法进行抽取"
        )
        raise FileNotFoundError("找不到 「抽取列表.txt」 文件")

    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow(VERSION)
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec())
